<script setup>
import { queryCategoryAll, addCategory, updateCategory, deleteCategory } from "@/api/category";
import { ref, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus'

// 分类数据（树形结构）
const categoryList = ref([])
const tableRef = ref(null)

// 获取分类数据
const getCategory = async () => {
  try {
    const result = await queryCategoryAll()
    // 直接使用接口返回的树形结构数据（因为后端已返回 children）
    categoryList.value = result?.data || []
  } catch (error) {
    console.error('获取分类数据失败:', error)
    // 可在此处添加 Element Plus 的消息提示
  }
}
// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const currentCategory = ref({
  id: '',
  name: '',
  parentId: null
})

// 打开添加对话框
const openAddDialog = (parent = null) => {
  dialogTitle.value = parent ? `添加子类别 - ${parent.name}` : '添加商品类别';
  currentCategory.value = {
    id: '',
    name: '',
    parentId: parent ? parent.id : null
  };
  dialogVisible.value = true;
}

// 打开编辑对话框
const openEditDialog = (category) => {
  dialogTitle.value = '编辑商品类别';
  currentCategory.value = { ...category };
  dialogVisible.value = true;
}

// 保存分类
const saveCategory = async () => {
  try {
    if (!currentCategory.value.name.trim()) {
      ElMessage.warning('请输入类别名称');
      return;
    }
    if (currentCategory.value.id) {
      await updateCategory(currentCategory.value);
      ElMessage.success('更新成功');
    } else {
      await addCategory(currentCategory.value);
      ElMessage.success('添加成功');
    }
    dialogVisible.value = false;
    getCategory(); // 刷新树形数据
  } catch (error) {
    console.error('保存分类失败:', error);
    ElMessage.error('操作失败: ' + (error.response?.data?.message || error.message));
  }
}

// 删除分类
const handleDelete = async (category) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除"${category.name}"吗？此操作不可恢复。`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    await deleteCategory(category.id);
    ElMessage.success('删除成功');
    getCategory(); // 刷新树形数据
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('已取消删除');
    } else {
      console.error('删除失败:', error);
      ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message));
    }
  }
}

onMounted(() => {
  getCategory().then(()=>{
    nextTick(()=>{
      tableRef.value?.expandAll();
    })
  });
})
</script>

<template>
  <div>
    <div style="margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center;">
      <h3>商品类别管理</h3>
      <el-button type="primary" @click="openAddDialog()">
        <i class="el-icon-plus"></i> 添加类别
      </el-button>
    </div>

    <!-- 商品类别表格 - 树形展示 -->
    <el-table 
      ref="tableRef"
      :data="categoryList" 
      style="width: 100%" 
      row-key="id" 
      border 
      :tree-props="{ 
        children: 'children', // 关联构建后的 children 数组
        hasChildren: 'hasChildren' 
      }"
    >
      <el-table-column type="index" label="#" width="50" align="center"></el-table-column>
      
      <el-table-column label="商品类别" min-width="200">
        <template #default="{ row }">
          {{ row.name }}
        </template>
      </el-table-column>
      
      <el-table-column prop="createBy" label="创建人" width="120" align="center"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160" align="center">
        <template #default="{ row }">
          {{ row.createTime ? new Date(row.createTime).toLocaleString() : '-' }}
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="200" align="center" fixed="right">
        <template #default="{ row }">
          <el-button 
            size="mini" 
            type="primary" 
            @click="openAddDialog(row)"
            v-if="!row.parentId"
          >
            添加子类
          </el-button>
          <el-button 
            size="mini" 
            type="warning" 
            @click="openEditDialog(row)"
          >
            编辑
          </el-button>
          <el-button 
            size="mini" 
            type="danger" 
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑/添加对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form :model="currentCategory" label-width="80px">
        <el-form-item label="类别名称" prop="name">
          <el-input 
            v-model="currentCategory.name" 
            placeholder="请输入类别名称"
            maxlength="50"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveCategory">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.el-table {
  margin-top: 20px;
}

.el-button + .el-button {
  margin-left: 8px;
}
</style>